package com.System.LearnSystemAdmin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.System.LearnSystem.MYSQL;
import com.System.LearnSystem.Result;
import com.System.LearnSystem.Teacher;
import com.System.LearnSystem.Token;
import com.System.LearnSystem.User;
import com.System.LearnSystem.sqlConnection;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

class teacher extends Teacher
{
	private String token;
	
	public teacher()
	{
		
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}
}

@WebServlet("/adm/addtea")
public class addteacher extends HttpServlet{
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		StringBuilder json = new StringBuilder();//读取json请求
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        String jsonStr = json.toString();     
        ObjectMapper objectMapper = new ObjectMapper();
        teacher tk = objectMapper.readValue(jsonStr, teacher.class);
        
        objectMapper.registerModule(new JavaTimeModule());//注册驱动保证序列化
        res.setContentType("application/json;charset=UTF-8");//设置响应格式
        PrintWriter out = res.getWriter();
        
        if(tk.getToken()!=null) 
        {
        	if(Token.checkToken(tk.getToken())&&"ADMIN".equals(tk.getRole()))//验证令牌和身份
        	{
        		if(!MYSQL.checkUserExists(tk.getUsername())&&!MYSQL.checkteaNoExists(tk.getTeacherNo()))
        		{	
        			String sql = "INSERT INTO t_user (username,password,role) VALUES (?,'123456','TEACHER');";//默认密码123456
		        	try (Connection conn = sqlConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) 
		        	{
		        		
		        		pstmt.setString(1,tk.getUsername());
		        		int Line = pstmt.executeUpdate();
		        		System.out.println("受影响的行数为："+Line);
		        		tk.setPassword("123456");
		        		tk.setRole("TEACHER");
		        	} catch (SQLException e) {
		      		  System.err.println("SQL 错误码: " + e.getErrorCode());
		      		  System.err.println("SQL 错误消息: " + e.getMessage());
		      		    e.printStackTrace();
					}
		        	
		        	sql = "INSERT INTO t_teacher (username,teacher_no,department_id,name) VALUES (?,?,?,?);";//默认密码123456
		        	try (Connection conn = sqlConnection.getConnection();PreparedStatement pstmt = conn.prepareStatement(sql)) 
		        	{
		        		pstmt.setString(1,tk.getUsername());
		        		pstmt.setString(2,tk.getTeacherNo());
		        		pstmt.setLong(3,tk.getDepartmentId());
		        		pstmt.setString(4,tk.getName());
		        		int Line = pstmt.executeUpdate();
		        		System.out.println("受影响的行数为："+Line);		        		
		        	} catch (SQLException e) {
		      		  System.err.println("SQL 错误码: " + e.getErrorCode());
		      		  System.err.println("SQL 错误消息: " + e.getMessage());
		      		    e.printStackTrace();
					}
		        	Result<teacher> result = Result.success(tk);
		        	out.println(objectMapper.writeValueAsString(result));
        		}
        		else
        		{
        			Result<Object> result = Result.error(200,"该用户名或教师编号已存在！");
        			out.println(objectMapper.writeValueAsString(result));
        			
        		}
        	}
        	else
        	{
        		Result<Object> result = Result.error(401,"非授权访问");
        		out.println(objectMapper.writeValueAsString(result));
        	}
        }
        else
        {
        	Result<Object> result = Result.error(401,"非授权访问");
        	out.println(objectMapper.writeValueAsString(result));
        }
	}
}
